<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="本节将详细分析Netty事件传播机制，即事件链的实现机制。 本文重点的行文思路：  详解事件的触发事件 事件传播机制 思考题：在NIO中是通道是一定需要注册写事件才能通过该通道写数据吗？">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty4 事件处理传播机制">
<meta property="og:url" content="https://www.codingw.net/posts/be152999.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="本节将详细分析Netty事件传播机制，即事件链的实现机制。 本文重点的行文思路：  详解事件的触发事件 事件传播机制 思考题：在NIO中是通道是一定需要注册写事件才能通过该通道写数据吗？">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20201213215532749.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20201213215634424.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20201213215730318.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2020121321581174.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20201213215906969.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20201213215946585.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="article:published_time" content="2020-12-19T14:11:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:32:56.147Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20201213215532749.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/be152999.html"/>





  <title>Netty4 事件处理传播机制 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/be152999.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Netty4 事件处理传播机制</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-19T22:11:01+08:00">
                2020-12-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/netty4/" itemprop="url" rel="index">
                    <span itemprop="name">netty4</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/be152999.html" class="leancloud_visitors" data-flag-title="Netty4 事件处理传播机制">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>本节将详细分析Netty事件传播机制，即事件链的实现机制。</p>
<p>本文重点的行文思路：</p>
<ul>
<li>详解事件的触发事件</li>
<li>事件传播机制</li>
<li>思考题：在NIO中是通道是一定需要注册写事件才能通过该通道写数据吗？</li>
</ul>
<span id="more"></span>

<p>Netty4的事件链核心类如图所示：<br><img src="https://img-blog.csdnimg.cn/20201213215532749.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>接下先详细介绍上述核心类的核心方法。<br>1、ChannelPipeline<br>“Channel流水线”，即Channel管道（事件处理链），其主要核心方法包括如下三类。<br><strong>添加类操作</strong></p>
<ul>
<li>ChannelPipeline addFirst(String name, ChannelHandler handler)</li>
<li>ChannelPipeline addFirst(EventExecutorGroup group, String name, ChannelHandler handler)</li>
<li>ChannelPipeline addFirst(ChannelHandler… handlers)</li>
<li>ChannelPipeline addFirst(EventExecutorGroup group, ChannelHandler… handlers)</li>
<li>ChannelPipeline addLast(String name, ChannelHandler handler)</li>
<li>ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler)</li>
<li>ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler)</li>
</ul>
<p>其中省略了addLast、addBefore、addAfter的其他重载方法，模式为addFirst类似。在这里着重讲解一下各个参数的含义。</p>
<ul>
<li>EventExecutorGroup group<br>ChannelHandler执行的线程组EventLoop，如果为空，则ChannelHandler在Channel所注册的EventLoop。</li>
<li>String name<br>ChannelHandler的名称，DefaultChannelPipeline会避免因重名而修改ChannelHandler的名称。</li>
</ul>
<p><strong>ChannelHandler的增删改查</strong></p>
<ul>
<li>ChannelPipeline remove(ChannelHandler handler)<br>ChannelHandler removeFirst()<br>省略其他API，此类API其实能反映出ChannelPipeline内部是一个双链表结构。</li>
</ul>
<p><strong>入端(inbound)事件传播</strong></p>
<ul>
<li>ChannelPipeline fireChannelRegistered()</li>
<li>ChannelPipeline fireChannelUnregistered()</li>
<li>ChannelPipeline fireChannelActive()</li>
<li>ChannelPipeline fireChannelInactive()</li>
<li>ChannelPipeline fireExceptionCaught(Throwable cause)</li>
<li>ChannelPipeline fireUserEventTriggered(Object event)</li>
<li>ChannelPipeline fireChannelRead(Object msg)</li>
<li>ChannelPipeline fireChannelReadComplete()</li>
<li>ChannelPipeline fireChannelWritabilityChanged()<br>不难看出，此类API方法名 fire + ChannelInboundHandler 中的方法。特别注意的是fireChannelRead(Object msg)的参数为通过网络SocketChannel#read一次读取的字节数组（ByteBuf），跟随着事件处理器一步一步的处理。</li>
</ul>
<p><strong>出端(outbound)事件传播</strong></p>
<ul>
<li>ChannelFuture bind(SocketAddress localAddress)</li>
<li>ChannelFuture connect(SocketAddress remoteAddress)</li>
<li>ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress)</li>
<li>ChannelFuture disconnect()</li>
<li>ChannelFuture close()</li>
<li>ChannelFuture deregister()</li>
<li>ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise)</li>
<li>ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise)</li>
<li>ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise)</li>
<li>ChannelFuture disconnect(ChannelPromise promise)</li>
<li>ChannelFuture close(ChannelPromise promise)</li>
<li>ChannelFuture deregister(ChannelPromise promise)</li>
<li>ChannelPipeline read()</li>
<li>ChannelFuture write(Object msg)</li>
<li>ChannelFuture write(Object msg, ChannelPromise promise)</li>
<li>ChannelPipeline flush()</li>
<li>ChannelFuture writeAndFlush(Object msg, ChannelPromise promise)</li>
<li>ChannelFuture writeAndFlush(Object msg)<br>不难看出，上述方法为ChannelOutboundHandler的方法。</li>
</ul>
<h2 id="2、DefaultChannelPipeline"><a href="#2、DefaultChannelPipeline" class="headerlink" title="2、DefaultChannelPipeline"></a>2、DefaultChannelPipeline</h2><p>ChannelPipeline的简单类图如下：<br><img src="https://img-blog.csdnimg.cn/20201213215634424.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>结合head、taill与下面的构造函数可知DefaultChannelPipeline的结构是其双链表，其中head、tail为双链表的首尾节点，并且其引用不能更改，其中节点（Node）实现为AbstractChannelHandlerContext，其内部必然定义两个属性prev与next，分别代表前一个节点与下一个节点。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> AbstractChannelHandlerContext head</span><br><span class="line"><span class="keyword">final</span> AbstractChannelHandlerContext tail</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Channel channel </span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="title">DefaultChannelPipeline</span><span class="params">(Channel channel)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.channel = ObjectUtil.checkNotNull(channel, <span class="string">&quot;channel&quot;</span>);</span><br><span class="line">        tail = <span class="keyword">new</span> TailContext(<span class="keyword">this</span>);</span><br><span class="line">        head = <span class="keyword">new</span> HeadContext(<span class="keyword">this</span>);</span><br><span class="line">        head.next = tail;</span><br><span class="line">        tail.prev = head;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>从这里看一个Channel对应一个ChannelPipeline。</p>
<h3 id="2-1-事件链构建"><a href="#2-1-事件链构建" class="headerlink" title="2.1 事件链构建"></a>2.1 事件链构建</h3><p>本节将以addFirst方法为例展示ChannelPipeline事件链的维护实现。<br>DefaultChannelPipeline#addFirst</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> ChannelPipeline <span class="title">addFirst</span><span class="params">(String name, ChannelHandler handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> addFirst(<span class="keyword">null</span>, name, handler);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>内部调用其重载方法。接下来重点分析该方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> ChannelPipeline <span class="title">addFirst</span><span class="params">(EventExecutorGroup group, String name, ChannelHandler handler)</span> </span>&#123;     <span class="comment">// @1</span></span><br><span class="line">        <span class="keyword">final</span> AbstractChannelHandlerContext newCtx;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            checkMultiplicity(handler);                                                                                                                        <span class="comment">// @2</span></span><br><span class="line">            name = filterName(name, handler);</span><br><span class="line">            newCtx = newContext(group, name, handler);                                                                                         <span class="comment">// @3</span></span><br><span class="line">            addFirst0(newCtx);                                                                                                                                   <span class="comment">// @4                                   </span></span><br><span class="line">            <span class="comment">// If the registered is false it means that the channel was not registered on an eventloop yet.</span></span><br><span class="line">            <span class="comment">// In this case we add the context to the pipeline and add a task that will call</span></span><br><span class="line">            <span class="comment">// ChannelHandler.handlerAdded(...) once the channel is registered.</span></span><br><span class="line">            <span class="keyword">if</span> (!registered) &#123;                                                                                                                                        <span class="comment">// @5</span></span><br><span class="line">                newCtx.setAddPending();</span><br><span class="line">                callHandlerCallbackLater(newCtx, <span class="keyword">true</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            EventExecutor executor = newCtx.executor();</span><br><span class="line">            <span class="keyword">if</span> (!executor.inEventLoop()) &#123;                                                                                                                  <span class="comment">// @6</span></span><br><span class="line">                newCtx.setAddPending();</span><br><span class="line">                executor.execute(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                        callHandlerAdded0(newCtx);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        callHandlerAdded0(newCtx);                                                                                                                    <span class="comment">// @7</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先对参数简单说明一下：</p>
<ul>
<li>EventExecutorGroup group：指定ChannelHandler在哪个事件选择器中执行(EventLoopGroup)，如果为空，表示在Channel注册的事件轮询器中执行。</li>
<li>String name：ChannelHandler名称。</li>
<li>ChannelHandler channelHandler：待添加的事件处理器。</li>
</ul>
<p>代码@2：检查是否重复添加，声明为Shareable的ChannelHandler允许重复添加。</p>
<p>代码@3：使用AbstractChannelHandlerContext类包装ChannelHandler，即双链表结构的Node类为AbstractChannelHandlerContext。</p>
<p>代码@4：将AbstractChannelHandlerContext调用addFirst0添加到双链表的“第一条”，其实是添加到双链表头结点(HeaderContext)的next值执行该节点。</p>
<p>代码@5-代码@7都是处理handerAdd事件，如果通道还未注册，handerAdd事件会“挂起”，也就是需要等待通道被注册后才执行，其实现思路也是构建PendingHandlerCallback链，DefaultChannelPipeline内部持有该链的头节点，待通道注册后，顺序触发handlerAdd事件的传播。</p>
<p>接下来看一下addFirst0的执行：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">addFirst0</span><span class="params">(AbstractChannelHandlerContext newCtx)</span> </span>&#123;</span><br><span class="line">        AbstractChannelHandlerContext nextCtx = head.next;    </span><br><span class="line">        newCtx.prev = head;                                                        </span><br><span class="line">        newCtx.next = nextCtx;                                                  </span><br><span class="line">        head.next = newCtx;                                                       </span><br><span class="line">        nextCtx.prev = newCtx;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>这里就是典型的链表操作过程。<br>如果使用如下代码构建事件链，那事件是如何传播的呢？<br>p.addLast(“1”, new InboundHandlerA());<br>p.addLast(“2”, new InboundHandlerB());<br>p.addLast(“3”, new OutboundHandlerA());<br>p.addLast(“4”, new OutboundHandlerB());<br>p.addLast(“5”, new InboundOutboundHandlerX());<br>其构建的事件链最终如图所示：<br><img src="https://img-blog.csdnimg.cn/20201213215730318.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>但ChannelInboundHandler中的事件是如何传播的呢？ChannelOutboundHandler的事件又是如何传播的呢？</p>
<p>事件链中的节点对象为AbstractChannelHandlerContext，其类图如下：</p>
<p><img src="https://img-blog.csdnimg.cn/2020121321581174.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
<ul>
<li>HeadContext：事件链的头节点。</li>
<li>TailContext：事件链的尾节点。</li>
<li>DefaultChannelHandlerContext：用户定义的Handler所在的节点。</li>
</ul>
<h3 id="2-2-事件传播"><a href="#2-2-事件传播" class="headerlink" title="2.2 事件传播"></a>2.2 事件传播</h3><p>inbound事件与outbound事件传播机制实现原理相同，只是方向不同，inbound事件的传播从HeadContext开始，沿着next指针进行传播，而outbound事件传播从TailContext开始，沿着prev指针向前传播，故下文重点分析inbound事件传播机制。</p>
<p>DefaultChannelPipeline有关于ChannelInboundHandler的方法实现如下：<br><img src="https://img-blog.csdnimg.cn/20201213215906969.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br><strong>所有的入端事件的传播入口都是从head开始传播</strong>。接下来我们以channelRead事件的传播为例，展示inbound的事件的流转。注意：以下观点都是针对NIO的读取。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">DefaultChannelPipeline#fireChannelRead(Object msg) &#123;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> ChannelPipeline <span class="title">fireChannelRead</span><span class="params">(Object msg)</span> </span>&#123;</span><br><span class="line">     AbstractChannelHandlerContext.invokeChannelRead(head, msg);  <span class="comment">// @1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>首先在NIO事件选择器在网络读事件就绪后，会调用底层SocketChanel#read 方法从读缓存中读取字节，在Netty中使用ByteBuf来存储，然后调用DefaultChannelPipeline # fireChannelRead 方法进行事件传播，每个ChannelHandler针对输入进行加工处理，ChannelPipeline因此而得名，有关Netty基于NIO的事件就绪选择实现将在Netty线程模型、IO读写流程部分详细讲解。</p>
<p>从代码@1处可得知，通过AbstractChannelHandlerContext的静态方法invokerChanelRead，从HeadContext处开始执行，</p>
<p>AbstractChannelHandlerContext#invokerChanelRead</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">invokeChannelRead</span><span class="params">(<span class="keyword">final</span> AbstractChannelHandlerContext next, <span class="keyword">final</span> Object msg)</span> </span>&#123;</span><br><span class="line">        ObjectUtil.checkNotNull(msg, <span class="string">&quot;msg&quot;</span>);</span><br><span class="line">        EventExecutor executor = next.executor();         <span class="comment">// @1</span></span><br><span class="line">        <span class="keyword">if</span> (executor.inEventLoop()) &#123;                                <span class="comment">// @2</span></span><br><span class="line">            next.invokeChannelRead(msg);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            executor.execute(<span class="keyword">new</span> Runnable() &#123;              <span class="comment">// @3</span></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                    next.invokeChannelRead(msg);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>这种写法是Netty处理事件执行的“模板”方法，都是先获取需要执行的线程组(EventLoop),如果当前线程不属于Eventloop，则将任务提交到EventLoop中异步执行，如果在，则直接调用。第一次调用，该next指针为HeadContext，那接下来重点关注一下HeadContext的invokeChannelRead方法。<br>AbstractChannelHandlerContext#invokeChannelRead</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">invokeChannelRead</span><span class="params">(Object msg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (invokeHandler()) &#123;                                                                            <span class="comment">// @1</span></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                ((ChannelInboundHandler) handler()).channelRead(<span class="keyword">this</span>, msg);   <span class="comment">// @2</span></span><br><span class="line">            &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">                notifyHandlerException(t);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            fireChannelRead(msg);                                                                     <span class="comment">// @3</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：如果该通道已经成功添加@1，则执行对应的事件@2，否则只是传播事件@3。</p>
<p>传播事件在AbstractChannelHandlerContext的实现思路如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">AbstractChannelHandlerContext#fireChannelRead</span><br><span class="line"><span class="function"><span class="keyword">public</span> ChannelHandlerContext <span class="title">fireChannelRead</span><span class="params">(<span class="keyword">final</span> Object msg)</span> </span>&#123;</span><br><span class="line">        invokeChannelRead(findContextInbound(), msg);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">private</span> AbstractChannelHandlerContext <span class="title">findContextInbound</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        AbstractChannelHandlerContext ctx = <span class="keyword">this</span>;</span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">            ctx = ctx.next;</span><br><span class="line">        &#125; <span class="keyword">while</span> (!ctx.inbound);</span><br><span class="line">        <span class="keyword">return</span> ctx;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>上述就从事件链中按顺序提取inbound类型的处理器，上述代码要最终能结束，那么TailContext必须是Inbound类型的事件处理器。</p>
<p>从代码@2中执行完对应的事件处理逻辑后，事件如何向下传播呢？如果需要继续将事件传播的话，请调用ChannelInboundHandlerAdapter 对应的传播事件方法，如上例中的 ChannelInboundHandlerAdapter#fireChannelRead，该方法会将事件链继续往下传播，如果在对应的事件处理中继续调用fireChannelRead，则事件传播则停止传播，也就是并不是事件一定会顺着整个调用链到达事件链的尾部TailContext，在实践中请特别重视。</p>
<p>Netty inbound 事件传播流程图如下：<br><img src="https://img-blog.csdnimg.cn/20201213215946585.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>上述主要分析了inboud事件的传播机制，为了加深理解，我们接下来浏览一下HeadContext、TailContext是如何实现各个事件方法的，这些事件，后续在梳理Netty读写流程时会再详细介绍。</p>
<h3 id="2-3-源码分析DefaultChannelPipeline-HeadContex"><a href="#2-3-源码分析DefaultChannelPipeline-HeadContex" class="headerlink" title="2.3 源码分析DefaultChannelPipeline$HeadContex"></a>2.3 源码分析DefaultChannelPipeline$HeadContex</h3><h4 id="2-3-1-HeadContext声明与构造方法"><a href="#2-3-1-HeadContext声明与构造方法" class="headerlink" title="2.3.1 HeadContext声明与构造方法"></a>2.3.1 HeadContext声明与构造方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">HeadContext</span> <span class="keyword">extends</span> <span class="title">AbstractChannelHandlerContext</span></span></span><br><span class="line"><span class="class">            <span class="keyword">implements</span> <span class="title">ChannelOutboundHandler</span>, <span class="title">ChannelInboundHandler</span> </span>&#123;    <span class="comment">// @1</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">final</span> Unsafe unsafe;                                                                     <span class="comment">// @2</span></span><br><span class="line"></span><br><span class="line">        HeadContext(DefaultChannelPipeline pipeline) &#123;                        </span><br><span class="line">            <span class="keyword">super</span>(pipeline, <span class="keyword">null</span>, HEAD_NAME, <span class="keyword">false</span>, <span class="keyword">true</span>);</span><br><span class="line">            unsafe = pipeline.channel().unsafe();</span><br><span class="line">            setAddComplete();</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：HeadContext实现ChannelInboundHandler与ChannelOutboundHandler，故它的inbound与outbound都返回true。<br>代码@2：Unsafe，Netty操作类。</p>
<h4 id="2-3-2-handlerAdded、handlerRemoved"><a href="#2-3-2-handlerAdded、handlerRemoved" class="headerlink" title="2.3.2 handlerAdded、handlerRemoved"></a>2.3.2 handlerAdded、handlerRemoved</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handlerAdded</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handlerRemoved</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ChanelHandler增加与移除事件处理逻辑：不做任何处理。为什么可以不传播呢？其实上文在讲解addFirst方法时已提到，在添加一个ChannelHandler到事件链时，会根据通道是否被注册，如果未注册，会先阻塞执行，DefaultChannelPipeline会保存一条执行链，等通道被注册后处触发执行，HeadContext作为一个非业务类型的事件处理器，对通道的增加与否无需关注。</p>
<h4 id="2-3-3-exceptionCaught"><a href="#2-3-3-exceptionCaught" class="headerlink" title="2.3.3 exceptionCaught"></a>2.3.3 exceptionCaught</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">exceptionCaught</span><span class="params">(ChannelHandlerContext ctx, Throwable cause)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            ctx.fireExceptionCaught(cause);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通道异常处理事件的处理逻辑：HeadContext的选择是自己不关注，直接将异常事件往下传播。</p>
<h4 id="2-3-4-channelRegistered"><a href="#2-3-4-channelRegistered" class="headerlink" title="2.3.4 channelRegistered"></a>2.3.4 channelRegistered</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRegistered</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            invokeHandlerAddedIfNeeded();</span><br><span class="line">            ctx.fireChannelRegistered();</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">invokeHandlerAddedIfNeeded</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">assert</span> channel.eventLoop().inEventLoop();</span><br><span class="line">        <span class="keyword">if</span> (firstRegistration) &#123;</span><br><span class="line">            firstRegistration = <span class="keyword">false</span>;</span><br><span class="line">            <span class="comment">// We are now registered to the EventLoop. It&#x27;s time to call the callbacks for the ChannelHandlers,</span></span><br><span class="line">            <span class="comment">// that were added before the registration was done.</span></span><br><span class="line">            callHandlerAddedForAllHandlers();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>通道注册事件处理逻辑：当通道成功注册后，判断是否是第一次注册，如果是第一次注册的话，调用所有的ChannelHandler#handlerAdd事件，因为当通道增加到事件链后，如果该通道还未注册，channelAdd事件不会马上执行，需要等通道注册后才执行，故在这里首先需要执行完挂起（延迟等待的任务）。然后调用fireChannelRegistered沿着事件链传播通道注册成功事件。</p>
<h4 id="2-3-5-channelUnregistered"><a href="#2-3-5-channelUnregistered" class="headerlink" title="2.3.5 channelUnregistered"></a>2.3.5 channelUnregistered</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelUnregistered</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            ctx.fireChannelUnregistered();</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Remove all handlers sequentially if channel is closed and unregistered.</span></span><br><span class="line">            <span class="keyword">if</span> (!channel.isOpen()) &#123;</span><br><span class="line">                destroy();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<p>通道取消注册事件处理逻辑：首先传播事件，然后判断通道的状态，如果是处于关闭状态（通道调用了close方法），则需要移除所有的ChannelHandler。</p>
<h4 id="2-3-6-channelActive"><a href="#2-3-6-channelActive" class="headerlink" title="2.3.6 channelActive"></a>2.3.6 channelActive</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"> 	ctx.fireChannelActive();</span><br><span class="line">        readIfIsAutoRead();</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>通道激活事件的处理逻辑（TCP连接建立成功后触发）：首先传播该事件，如果开启自动读机制(autoRead为true)，则调用Channel#read方法，向NIO Selector注册读事件。</p>
<h4 id="2-3-7-channelInactive"><a href="#2-3-7-channelInactive" class="headerlink" title="2.3.7 channelInactive"></a>2.3.7 channelInactive</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelInactive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">ctx.fireChannelInactive();</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>通道非激活事件处理逻辑：只传播事件。</p>
<h4 id="2-3-8-channelRead"><a href="#2-3-8-channelRead" class="headerlink" title="2.3.8 channelRead"></a>2.3.8 channelRead</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">ctx.fireChannelRead(msg);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通道读事件处理逻辑：向下传播事件，各个编码器、业务处理器将各自处理业务逻辑。</p>
<h4 id="2-3-9-channelReadComplete"><a href="#2-3-9-channelReadComplete" class="headerlink" title="2.3.9 channelReadComplete"></a>2.3.9 channelReadComplete</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelReadComplete</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">ctx.fireChannelReadComplete();</span><br><span class="line">readIfIsAutoRead();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通道读完成事件，首先先传播事件，然后如果开启了自动读取的话，继续注册读事件。</p>
<h4 id="2-3-10-userEventTriggered"><a href="#2-3-10-userEventTriggered" class="headerlink" title="2.3.10 userEventTriggered"></a>2.3.10 userEventTriggered</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">userEventTriggered</span><span class="params">(ChannelHandlerContext ctx, Object evt)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            ctx.fireUserEventTriggered(evt);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>用户自定义事件的处理逻辑：传播事件。</p>
<h4 id="2-3-11-channelWritabilityChanged"><a href="#2-3-11-channelWritabilityChanged" class="headerlink" title="2.3.11 channelWritabilityChanged"></a>2.3.11 channelWritabilityChanged</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelWritabilityChanged</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            ctx.fireChannelWritabilityChanged();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通道可写状态变更事件的处理逻辑：传播事件。</p>
<p>接下来介绍HeadContext对于ChannelOutboundHander事件的处理逻辑：</p>
<h4 id="2-3-12-bind"><a href="#2-3-12-bind" class="headerlink" title="2.3.12 bind"></a>2.3.12 bind</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">bind</span><span class="params">( ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise)</span></span></span><br><span class="line"><span class="function">                <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">unsafe.bind(localAddress, promise);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过Unsafe实例完成具体的绑定操作，后续会重点分析该方法的实现原理。</p>
<p>由于HeadContex是outbound事件的尾部事件处理器，而且outbound是用户发送的API调用，其最终目的是希望通过Netty完成具体的网络操作，故HeadContex是离Netty底层机制最近的，到了这里，就意味者“应用程序”层面的定制化介绍，最终需要通过HeadContex直接调用Netty的API来完成具体的动作，故HeadContex关于outbound事件的实现，都是通过调用unsafe去完成具体的动作。故后面的方面就不在一一罗列。</p>
<h3 id="2-3-源码分析DefaultChannelPipeline-TailContext"><a href="#2-3-源码分析DefaultChannelPipeline-TailContext" class="headerlink" title="2.3 源码分析DefaultChannelPipeline$TailContext"></a>2.3 源码分析DefaultChannelPipeline$TailContext</h3><p>TailContext由于是 inbound事件链的最后一站，故该节点大部分事件都是空实现，其他实现的方法，基本上就是释放一下资源，我们看一下TailContex关于channelRead事件的处理逻辑：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            onUnhandledInboundMessage(msg);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onUnhandledInboundMessage</span><span class="params">(Object msg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            logger.debug(</span><br><span class="line">                    <span class="string">&quot;Discarded inbound message &#123;&#125; that reached at the tail of the pipeline. &quot;</span> +</span><br><span class="line">                            <span class="string">&quot;Please check your pipeline configuration.&quot;</span>, msg);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            ReferenceCountUtil.release(msg);</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最后就是主动调用ReferenceCountUtil.release(msg)释放资源。</p>
<p>Netty事件传播机制就讲解到这里了。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/6c0cb4a9.html" rel="next" title="源码分析RateLimiter SmoothWarmingUp 实现原理(文末附流程图)">
                <i class="fa fa-chevron-left"></i> 源码分析RateLimiter SmoothWarmingUp 实现原理(文末附流程图)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/5cfc78e.html" rel="prev" title="源码阅读方法、误区与三种境界">
                源码阅读方法、误区与三种境界 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81DefaultChannelPipeline"><span class="nav-number">1.</span> <span class="nav-text">2、DefaultChannelPipeline</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E4%BA%8B%E4%BB%B6%E9%93%BE%E6%9E%84%E5%BB%BA"><span class="nav-number">1.1.</span> <span class="nav-text">2.1 事件链构建</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E4%BA%8B%E4%BB%B6%E4%BC%A0%E6%92%AD"><span class="nav-number">1.2.</span> <span class="nav-text">2.2 事件传播</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90DefaultChannelPipeline-HeadContex"><span class="nav-number">1.3.</span> <span class="nav-text">2.3 源码分析DefaultChannelPipeline$HeadContex</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-1-HeadContext%E5%A3%B0%E6%98%8E%E4%B8%8E%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95"><span class="nav-number">1.3.1.</span> <span class="nav-text">2.3.1 HeadContext声明与构造方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-2-handlerAdded%E3%80%81handlerRemoved"><span class="nav-number">1.3.2.</span> <span class="nav-text">2.3.2 handlerAdded、handlerRemoved</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-3-exceptionCaught"><span class="nav-number">1.3.3.</span> <span class="nav-text">2.3.3 exceptionCaught</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-4-channelRegistered"><span class="nav-number">1.3.4.</span> <span class="nav-text">2.3.4 channelRegistered</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-5-channelUnregistered"><span class="nav-number">1.3.5.</span> <span class="nav-text">2.3.5 channelUnregistered</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-6-channelActive"><span class="nav-number">1.3.6.</span> <span class="nav-text">2.3.6 channelActive</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-7-channelInactive"><span class="nav-number">1.3.7.</span> <span class="nav-text">2.3.7 channelInactive</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-8-channelRead"><span class="nav-number">1.3.8.</span> <span class="nav-text">2.3.8 channelRead</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-9-channelReadComplete"><span class="nav-number">1.3.9.</span> <span class="nav-text">2.3.9 channelReadComplete</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-10-userEventTriggered"><span class="nav-number">1.3.10.</span> <span class="nav-text">2.3.10 userEventTriggered</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-11-channelWritabilityChanged"><span class="nav-number">1.3.11.</span> <span class="nav-text">2.3.11 channelWritabilityChanged</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-12-bind"><span class="nav-number">1.3.12.</span> <span class="nav-text">2.3.12 bind</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90DefaultChannelPipeline-TailContext"><span class="nav-number">1.4.</span> <span class="nav-text">2.3 源码分析DefaultChannelPipeline$TailContext</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
